package com.founder.tool.xml;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

public class XmlUtil {
	
	private static XMLReader reader = null;
	
	public XmlUtil() throws Exception {
		if (reader == null) {
			SAXParserFactory spf = SAXParserFactory.newInstance();
			SAXParser sp = spf.newSAXParser();
			reader = sp.getXMLReader();
		}
	}
	
	public void parse(String xml, ContentHandler handle) throws IOException, SAXException {
		parse(new InputSource(new StringReader(xml)), handle);
	}
	
	public void parse(InputStream in, ContentHandler handle) throws IOException, SAXException {
		parse(new InputSource(in), handle);
	}
	
	public void parse(File file, ContentHandler handle) throws IOException, SAXException {
		FileInputStream in = new FileInputStream(file);
		try {
			parse(new InputSource(in), handle);
		} finally {
			in.close();
		}
	}
	
	public void parse(InputSource in, ContentHandler handle) throws IOException, SAXException {
		reader.setContentHandler(handle);
		reader.parse(in);
	}
}


